package com.rem.rabbitmq.boot.Adelay;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author Rem
 * @date 2021-12-30
 */

@Slf4j
@RestController
@RequestMapping("/delay")
@Api(tags = "延迟队列")
public class SendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @ApiOperation(value = "队列设置过期时间 的延迟消息")
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {

        log.info("当前时间：{},发送一条信息给两个TTL队列:{}", LocalDateTime.now(), message);

        rabbitTemplate.convertAndSend(QueueConfig.X_EXCHANGE, QueueConfig.XA_ROUTING_KEY, "消息来自ttl为10S的队列:" + message);

        rabbitTemplate.convertAndSend(QueueConfig.X_EXCHANGE, QueueConfig.XB_ROUTING_KEY, "消息来自ttl为40S的队列:" + message);
    }

    @ApiOperation(value = "消息设置过期时间 的延迟消息")
    @GetMapping("/sendMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime) {
        log.info("当前时间：{},发送一条信息:{}，,并且设置ttl:{}", LocalDateTime.now(), message, ttlTime);

        /**
         * setExpiration 设置过期时间
         */
        MessagePostProcessor messagePostProcessor = messageProperties -> {
            messageProperties.getMessageProperties().setExpiration(ttlTime);
            return messageProperties;
        };
        rabbitTemplate.convertAndSend(QueueConfig.X_EXCHANGE, QueueConfig.XC_ROUTING_KEY, message, messagePostProcessor);
    }

    @ApiOperation(value = "设置插件-发送生产端设置过期时间 的延迟消息")
    @GetMapping("/sendDelayMsg/{message}/{ttlTime}")
    public void sendDelayMsg(@PathVariable String message, @PathVariable Integer ttlTime) {
        log.info("当前时间：{},发送一条信息:{}，,使用延迟队列插件 并且设置ttl:{}", LocalDateTime.now(), message, ttlTime);

        /**
         * setDelay  设置延迟时间
         */
        MessagePostProcessor messagePostProcessor = messageProperties -> {
            messageProperties.getMessageProperties().setDelay(ttlTime);
            return messageProperties;
        };
        rabbitTemplate.convertAndSend(DelayQueueConfig.DELAY_EXCHANGE, DelayQueueConfig.DELAY_ROUTING_KEY, message, messagePostProcessor);
    }

}
